﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using DeliveryPlus.Web.Controllers;
using DeliveryPlus.Web.DAL.Entities;

namespace DeliveryPlus.Web.Areas.ControlPanel.Controllers
{
    /// <summary>
    /// Контроллер управления блюдами
    /// </summary>
    public class ManageDishesController : BaseController
    {
        /// <summary>
        /// Контроллер управления блюдами в системе
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(long? cafeId)
        {
            IEnumerable<Dishe> dishes = DataContext.Dishes.Where(i => i.Hidden == false).OrderBy(d => d.Title);
            if (cafeId.HasValue)
            {
                dishes = dishes.Where(d => d.CafeId == cafeId.Value);
            }
            return View(dishes.ToList());
        }

        /// <summary>
        /// Отображает форму добавления нового блюда на сайт
        /// </summary>
        /// <param name="cafeId">Идентификатор блюда</param>
        /// <returns></returns>
        public ActionResult Add(long? cafeId)
        {
            return View("EditDish", new Dishe()
            {
                CafeId = cafeId.HasValue ? cafeId.Value : 0
            });
        }

        /// <summary>
        /// Отображает форму редактирования блюда
        /// </summary>
        /// <param name="id">Идентификатор блюда</param>
        /// <returns></returns>
        public ActionResult Edit(long id)
        {
            var dish = DataContext.Dishes.FirstOrDefault(d => d.Id == id);
            if (dish == null || dish.Hidden)
            {
                return RedirectToAction("Index");
            }

            return View("EditDish", dish);
        }

        /// <summary>
        /// Обрабатывает редактированию блюда или создание нового
        /// </summary>
        /// <param name="model">Модель данных</param>
        /// <param name="next">Если next задано то после создания блюда будет отображения форма добвления еще одного блюда</param>
        /// <param name="collection">Коллекция данных форм</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(Dishe model, string next, FormCollection collection)
        {
            // Сохраняем файл
            var photoFile = Request.Files["photoFile"];
            var photoFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files", "Dish", Path.GetRandomFileName());
            photoFilePath = Path.ChangeExtension(photoFilePath, ".jpg");
            string photoFileName = null;
            if (photoFile != null && photoFile.ContentLength > 0 && photoFile.ContentType.Contains("image"))
            {
                photoFile.SaveAs(photoFilePath);
                photoFileName = Path.GetFileName(photoFilePath);
            }

            var types = String.Join(",",
                collection.AllKeys.Where(k => k.StartsWith("types-")).Select(k => k.Split('-')[1]));

            if (model.Id <= 0)
            {
                model.DateCreated = DateTime.Now;
                model.Photo = photoFileName;
                model.Types = types;
                DataContext.Dishes.InsertOnSubmit(model);
                DataContext.SubmitChanges();
            }
            else // 93-40-40
            {
                var dish = DataContext.Dishes.FirstOrDefault(d => d.Id == model.Id);
                if (dish == null)
                {
                    return RedirectToAction("Index");
                }

                dish.Title = model.Title;
                dish.Description = model.Description;
                dish.Weight = model.Weight;
                dish.Energy = model.Energy;
                dish.Hidden = model.Hidden;
                dish.Price = model.Price;
                dish.Types = types;
                dish.Photo = photoFileName ?? dish.Photo;
                dish.DateModified = DateTime.Now;

                if (model.CafeId != dish.CafeId)
                {
                    dish.Cafe.Dishes.Remove(dish);
                    DataContext.Cafes.First(c => c.Id == model.CafeId).Dishes.Add(dish);
                }

                if (model.TypeId != dish.TypeId)
                {
                    if (dish.DishType != null)
                    {
                        dish.DishType.Dishes.Remove(dish);
                    }
                    if (model.TypeId != -1)
                    {
                        DataContext.DishTypes.First(t => t.Id == model.TypeId).Dishes.Add(dish);
                    }
                    else
                    {
                        dish.DishType = null;
                    }
                }

                DataContext.SubmitChanges();
            }

            if (!String.IsNullOrEmpty(next))
            {
                return RedirectToAction("Add", new {cafeId = model.CafeId});
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        /// <summary>
        /// Удаляет указанное блюдо
        /// </summary>
        /// <param name="id">Идентификатор блюда</param>
        /// <returns></returns>
        public ActionResult Delete(long id)
        {
            var dish = DataContext.Dishes.FirstOrDefault(d => d.Id == id);
            if (dish == null)
            {
                return RedirectToAction("Index");
            }

            dish.Hidden = true;

            //DataContext.Dishes.DeleteOnSubmit(dish);
            DataContext.SubmitChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Массово изменяет тип указанных блюд
        /// </summary>
        /// <param name="ids">Идентификаторы блюд</param>
        /// <param name="typeId">Новый идентификатор типа</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangeTypes(string ids, long typeId)
        {
            var dishes =
                (ids ?? "").Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
                    .Select(c => Convert.ToInt64(c))
                    .Select(c => DataContext.Dishes.FirstOrDefault(d => d.Id == c))
                    .Where(d => d != null)
                    .ToList();

            foreach (var dish in dishes)
            {
                if (typeId != dish.TypeId)
                {
                    if (dish.DishType != null)
                    {
                        dish.DishType.Dishes.Remove(dish);
                    }
                    if (typeId != -1)
                    {
                        DataContext.DishTypes.First(t => t.Id == typeId).Dishes.Add(dish);
                    }
                    else
                    {
                        dish.DishType = null;
                    }
                    dish.DateModified = DateTime.Now;
                }
            }

            DataContext.SubmitChanges();

            return RedirectToAction("Index");
        }
    }
}
